package com.hskn.hss.module.tlequip.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hskn.hss.core.annotation.SysLog;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.enums.BusinessType;
import com.hskn.hss.core.utils.file.FileTypeUtils;
import com.hskn.hss.core.utils.poi.ExcelUtil;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.common.ienum.ExcelTypeEnum;
import com.hskn.hss.module.common.to.ExcelReaderTO;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.equiptype.entity.TlEquiptype;
import com.hskn.hss.module.equiptype.mapper.TlEquiptypeMapper;
import com.hskn.hss.module.manufacturer.entity.TlManufacturer;
import com.hskn.hss.module.manufacturer.mapper.TlManufacturerMapper;
import com.hskn.hss.module.tlequip.entity.TlEquip;
import com.hskn.hss.module.tlequip.mapper.TlEquipMapper;
import com.hskn.hss.module.tlequip.service.ITlEquipService;
import com.hskn.hss.module.tlequip.to.TIEquipExportTo;
import com.hskn.hss.module.tlequip.vo.TlEquipExcelOutVO;
import com.hskn.hss.module.tlequipmodel.entity.TlEquipmodel;
import com.hskn.hss.module.tlequipmodel.mapper.TlEquipmodelMapper;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author hskn
 * @since 2021-05-11
 */
@Api(tags = {"-tl_equip"}, description = "设备档案")
@Slf4j
@RestController
@RequestMapping("/hss/tlequip")
public class TlEquipController {

    @Autowired
    ITlEquipService tlEquipService;
    @Resource
    TlEquipMapper tlEquipMapper;
    @Autowired
    private ISysDepartService departService;
    @Resource
    private TlEquipmodelMapper tlEquipmodelMapper;
    @Resource
    private TlManufacturerMapper tlManufacturerMapper;
    @Resource
    private TlEquiptypeMapper tlEquiptypeMapper;

    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_equip", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @RequestMapping(value = "insert", method = RequestMethod.POST)
    public AjaxResult<Object> insert(@RequestBody @Validated TlEquip tlEquip,HttpServletRequest request) {
        try {
            QueryWrapper<TlEquip> tlEquipQueryWrapper = new QueryWrapper<>();
            tlEquipQueryWrapper.lambda().eq(TlEquip::getEquipcode, tlEquip.getEquipcode());
            List<TlEquip> equipList = tlEquipMapper.selectList(tlEquipQueryWrapper);
            if (equipList.isEmpty()) {
                tlEquipService.insert(tlEquip);
                return AjaxResult.success(tlEquip);
            } else {
                return AjaxResult.fail("该名称已存在，请重新输入");
            }

        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_equip", idKey = "id", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public AjaxResult<Object> update(HttpServletRequest request) {
        try {
            JSONObject params = JSON.parseObject(Tools.getBody(request));
            return tlEquipService.update(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.UPDATE, tableName = "tl_equip", idKey = "ids", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @ApiOperation(value = "批量更新接口", notes = "批量更新")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEquip.class)
    })
    @RequestMapping(value = "updatebyids", method = RequestMethod.POST)
    public AjaxResult<Object> updatebyids(@RequestBody @Validated TlEquip tlEquip ,HttpServletRequest request) {
        try {
            return tlEquipService.updatebyids(tlEquip);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("操作失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_equip", idKey = "id", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @RequestMapping(value = "deletebyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebyid(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            return tlEquipService.deletebyid(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @SysLog(businessType = BusinessType.DELETE, tableName = "tl_equip", idKey = "ids", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @ApiOperation(value = "批量删除接口", notes = "批量删除")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = TlEquip.class)
    })
    @RequestMapping(value = "deletebatchbyid", method = RequestMethod.POST)
    public AjaxResult<Object> deletebatchbyid(@RequestBody @Validated TlEquip tlEquip) {

        try {
            return tlEquipService.deletebatchbyid(tlEquip);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("删除失败，请稍后再试");
        }
    }

    @RequestMapping(value = "getSelectList", method = RequestMethod.POST)
    public AjaxResult<Object> getSelectList(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        return AjaxResult.success(tlEquipService.getSelectList(params));
    }

    @RequestMapping(value = "getDetail", method = RequestMethod.POST)
    public AjaxResult<Object> getDetail(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        TlEquip tlEquip = null;
        try {
            tlEquip = tlEquipService.getDetail(params);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }
        return AjaxResult.success(tlEquip);

    }

    @RequestMapping(value = "getList", method = RequestMethod.POST)
    public AjaxResult<Object> getList(HttpServletRequest request) {
        JSONObject params = JSON.parseObject(Tools.getBody(request));
        try {
            BaseEntity entity = new BaseEntity();
            JSONObject json = tlEquipService.getList(entity, params);
            return AjaxResult.success(json);
        } catch (HssException e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }

    /**
     * 获取列表
     *
     * @param request
     * @return
     */
//    @SysLog(businessType = BusinessType.INSERT, tableName = "tl_equip", bean = TlEquip.class, beanMapper = TlEquipMapper.class, names = "equipname,equipcode")
    @ApiOperation(value = "设备档案导入接口", notes = "设备档案导入")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelReader")
    public AjaxResult excelReader(HttpServletRequest request,  @Validated ExcelReaderTO excelReaderTo) {
        try {
            MultipartFile file=excelReaderTo.getFiles();
            if(Arrays.stream(ExcelTypeEnum.values()).noneMatch(s->s.getName().equals(FileTypeUtils.getFileType(file.getOriginalFilename().toLowerCase())))){
                return AjaxResult.fail("导入文件格式错误");
            }
            InputStream inputStream = new BufferedInputStream(file.getInputStream());
            ExcelUtil<TlEquip> util = new ExcelUtil<TlEquip>(TlEquip.class);
            List<TlEquip> TlEquipList = util.importExcel(inputStream);
            if(TlEquipList.isEmpty()){
                return AjaxResult.fail("导入内容为空");
            }
            tlEquipService.excelReader(TlEquipList);

            if (tlEquipService.saveBatch(TlEquipList)) {
                return AjaxResult.success();
            } else {
                return AjaxResult.fail("导入失败");
            }
        } catch (ExcelReaderDataException e) {
            return AjaxResult.fail(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }
    
    @ApiOperation(value = "设备档案导出接口", notes = "设备档案导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok")
    })
    @PostMapping("excelExport")
    public com.hskn.hss.core.domain.AjaxResult excelExport(HttpServletRequest request,@RequestBody TIEquipExportTo tiEquipExportTo) {
        try {
            if((tiEquipExportTo.getIds()!=null&&tiEquipExportTo.getIds().isEmpty())){
                return com.hskn.hss.core.domain.AjaxResult.error("请选择至少一条数据导出");
            }
            QueryWrapper<TlEquip> tlEquipQueryWrapper=new QueryWrapper<>();
            QueryWrapper<TlEquipmodel> tlEquipmodelQueryWrapper=new QueryWrapper<>();
            QueryWrapper<TlManufacturer> tlManufacturerQueryWrapper=new QueryWrapper<>();
            QueryWrapper<TlEquiptype> tlEquiptypeQueryWrapper=new QueryWrapper<>();
            if(StringUtils.isNotEmpty(tiEquipExportTo.getBindtype())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getBindtype,tiEquipExportTo.getBindtype());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getBindstatus())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getBindstatus,tiEquipExportTo.getBindstatus());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getCommunicationcode())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getCommunicationcode,tiEquipExportTo.getCommunicationcode());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getEquipcode())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getEquipcode,tiEquipExportTo.getEquipcode());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getStatus())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getStatus,tiEquipExportTo.getStatus());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getBindobjid())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getBindobjid,tiEquipExportTo.getBindobjid());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getEquipname())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getEquipname,tiEquipExportTo.getEquipname());
            }
            if(StringUtils.isNotEmpty(tiEquipExportTo.getEquiptypeid())){
                tlEquipQueryWrapper.lambda().eq(TlEquip::getEquiptypeid,tiEquipExportTo.getEquiptypeid());
            }
            if(tiEquipExportTo.getIds()!=null&&!tiEquipExportTo.getIds().isEmpty()){
                tlEquipQueryWrapper.lambda().in(TlEquip::getId,tiEquipExportTo.getIds());
            }
            List<TlEquip> tlEquipList=tlEquipMapper.selectList(tlEquipQueryWrapper);



            if(tlEquipList.isEmpty()){
                return com.hskn.hss.core.domain.AjaxResult.error("导出数据为空");
            }
            ExcelUtil<TlEquipExcelOutVO> util = new ExcelUtil<TlEquipExcelOutVO>(TlEquipExcelOutVO.class);
            List<TlEquipExcelOutVO> TlEquipExcelOutVOList=JSONObject.parseArray(JSONObject.toJSONString(tlEquipList),TlEquipExcelOutVO.class);
            Map<String, SysDepart> departMap=departService.getDepartMap(new QueryWrapper<>());
            List<TlEquipmodel> tlEquipmodelList= tlEquipmodelMapper.selectList(tlEquipmodelQueryWrapper);
            Map<String, TlEquipmodel>  tlEquipmodelMap = GroupingByUtils.getGroupingForMapEntity(tlEquipmodelList, TlEquipmodel::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
            List<TlManufacturer> tlManufacturerList= tlManufacturerMapper.selectList(tlManufacturerQueryWrapper);
            Map<String, TlManufacturer>  tlManufacturerMap = GroupingByUtils.getGroupingForMapEntity(tlManufacturerList, TlManufacturer::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
            List<TlEquiptype> tlEquiptypeList= tlEquiptypeMapper.selectList(tlEquiptypeQueryWrapper);
            Map<String, TlEquiptype>  tlEquiptypeMap = GroupingByUtils.getGroupingForMapEntity(tlEquiptypeList, TlEquiptype::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));

            for(TlEquipExcelOutVO TlEquipExcelOutVO:TlEquipExcelOutVOList){
                if(tlEquiptypeMap.containsKey(TlEquipExcelOutVO.getEquiptypeid())){
                    TlEquipExcelOutVO.setEquiptype(tlEquiptypeMap.get(TlEquipExcelOutVO.getEquiptypeid()).getEquipname());
                }
                if(tlEquipmodelMap.containsKey(TlEquipExcelOutVO.getEquipmodelid())){
                    TlEquipExcelOutVO.setEquipmodel(tlEquipmodelMap.get(TlEquipExcelOutVO.getEquipmodelid()).getEquipmodel());
                }
                if(tlManufacturerMap.containsKey(TlEquipExcelOutVO.getManufacturerid())){
                    TlEquipExcelOutVO.setManufacturername(tlManufacturerMap.get(TlEquipExcelOutVO.getManufacturerid()).getManufacturername());
                }
            }
            return util.exportExcel(TlEquipExcelOutVOList,"设备档案");

        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }
    
    @ApiOperation(value = "设备档案导出模板接口", notes = "设备档案模板导出")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok",response = TlEquipExcelOutVO.class)
    })
    @PostMapping("excelExportTemplate")
    public com.hskn.hss.core.domain.AjaxResult excelExportTemplate(HttpServletRequest request) {
        try {
            //工具类实例化
            ExcelUtil<TlEquip> util = new ExcelUtil<TlEquip>(TlEquip.class);
            //数据载体转换
            List<TlEquip> tlEquipList=new ArrayList<>();
            //导出
            return util.exportExcel(tlEquipList,"设备档案模板");
        } catch (Exception e) {
            e.printStackTrace();
            return com.hskn.hss.core.domain.AjaxResult.error();
        }

    }

    @ApiOperation(value = "获取设施视频设备信息", notes = "包括通道信息")
    @ApiResponses({@ApiResponse(code = 200, message = "ok")})
    @PostMapping("/getEquipWithChannel")
    public AjaxResult<Object> getEquipWithChannel(HttpServletRequest request) {
        try {
            List<TlEquipExcelOutVO> list = tlEquipService.getEquipWithChannel();
            return AjaxResult.success(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("报错ERROR", e);
            return AjaxResult.fail("获取信息失败，请稍后再试");
        }

    }
}

